﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using System.Web.UI;
using System.Net;
using System.Web.Services;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Security;
using Microsoft.BusinessData.Infrastructure.SecureStore;
using Microsoft.Office.SecureStoreService.Server;
using System.Linq;
using System.Web.UI.WebControls;

namespace TFSWITConnector
{
    public partial class CustomLobSystemData : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //base.OnLoad(e);
            if (!this.IsPostBack)
            {
                var spPropBag = SPControl.GetContextSite(Context).RootWeb.Properties;
                
                var sssSelectOptions = GetSSSApplicationIDs();
                if (sssSelectOptions != null)
                {
                    this.rdbSSS2.Disabled = false;
                    if (spPropBag.ContainsKey("LobSystem_TFSCredentials"))
                    {
                        this.rdbSPU2.Checked = spPropBag["LobSystem_TFSCredentials"] == "SPU";
                        this.rdbSSS2.Checked = spPropBag["LobSystem_TFSCredentials"] == "SSS";
                    }
                    else
                    {
                        this.rdbSPU2.Checked = true;
                        this.rdbSSS2.Checked = false;
                    }

                    this.sssUserSelector2.Items.AddRange(sssSelectOptions.Select(x => new ListItem(x)).ToArray());

                    this.sssUserSelector2.Disabled = this.rdbSPU2.Checked;
                    if (spPropBag.ContainsKey("LobSystem_AppID") && !string.IsNullOrEmpty(spPropBag["LobSystem_AppID"]))
                        this.sssUserSelector2.Value = spPropBag["LobSystem_AppID"];
                }
                else
                {
                    this.rdbSPU2.Checked = true;
                    this.rdbSSS2.Checked = false;
                    this.sssUserSelector2.Disabled = true;
                    this.rdbSSS2.Disabled = true;
                }

                var LobSysDefaults = new TFSSPConnector.CustomLobSystemStructure();

                this.txtAttachment_EntityName.Text = (spPropBag.ContainsKey("Attachment_EntityName") ? (string)spPropBag["Attachment_EntityName"] : LobSysDefaults.Attachment_EntityName);
                this.txtAttachment_ShowInItemView.Text = (spPropBag.ContainsKey("Attachment_ShowInItemView") ? (string)spPropBag["Attachment_ShowInItemView"] : LobSysDefaults.Attachment_ShowInItemView);
                this.txtAttachment_ShowInListView.Text = (spPropBag.ContainsKey("Attachment_ShowInListView") ? (string)spPropBag["Attachment_ShowInListView"] : LobSysDefaults.Attachment_ShowInListView);

                this.txtLobSystem_Name.Text = (spPropBag.ContainsKey("LobSystem_Name") ? (string)spPropBag["LobSystem_Name"] : LobSysDefaults.LobSystem_Name);
                this.txtLobSystem_TFSProjectName.Text = (spPropBag.ContainsKey("LobSystem_TFSProjectName") ? (string)spPropBag["LobSystem_TFSProjectName"] : LobSysDefaults.LobSystem_TFSProjectName);
                this.txtLobSystem_TFSServerURL.Text = (spPropBag.ContainsKey("LobSystem_TFSServerURL") ? (string)spPropBag["LobSystem_TFSServerURL"] : LobSysDefaults.LobSystem_TFSServerURL);

                this.txtWorkItem_ReadOnlyFields.Text = (spPropBag.ContainsKey("WorkItem_ReadOnlyFields") ? (string)spPropBag["WorkItem_ReadOnlyFields"] : LobSysDefaults.WorkItem_ReadOnlyFields);
                this.txtWorkItem_RequiredInForms.Text = (spPropBag.ContainsKey("WorkItem_RequiredInForms") ? (string)spPropBag["WorkItem_RequiredInForms"] : LobSysDefaults.WorkItem_RequiredInForms);
                this.txtWorkItem_ShowInItemView.Text = (spPropBag.ContainsKey("WorkItem_ShowInItemView") ? (string)spPropBag["WorkItem_ShowInItemView"] : LobSysDefaults.WorkItem_ShowInItemView);
                this.txtWorkItem_ShowInListView.Text = (spPropBag.ContainsKey("WorkItem_ShowInListView") ? (string)spPropBag["WorkItem_ShowInListView"] : LobSysDefaults.WorkItem_ShowInListView);
            }
        }

        public static string[] GetSSSApplicationIDs()
        {
            string[] ids = null;

            try
            {
                SecureStoreProvider prov = new SecureStoreProvider();
                prov.Context = SPServiceContext.Current;
                ids = prov.GetTargetApplications().Select(x => x.Name).ToArray();
            }
            catch (Exception) {}

            return ids;
        }

        internal static SecureStoreCredentialCollection GetSSSCredentials(string LobSystem_AppID, out string errmessage)
        {
            errmessage = null;
            if (string.IsNullOrEmpty(LobSystem_AppID)) return null;

            SecureStoreProvider prov = new SecureStoreProvider();
            prov.Context = SPServiceContext.Current;
            try
            {
                var cc = prov.GetCredentials(LobSystem_AppID);
                return cc;
            }
            catch (Exception ex)
            {
                errmessage = ex.Message;
            }

            return null;
        }

        [WebMethod]
        public static string ValidateTFSConnection(string url, string user)
        {
            string message = null;
            if (string.IsNullOrEmpty(url))
            {
                return "TFS connection string is empty";
            }

            var LobSystem_AppID = GetSSSCredentials(user, out message);
            if (message != null) return message;

            bool res = TFSSPConnector.CustomLobSystem.ValidateTFSConnection(url, LobSystem_AppID, out message);
            if (!res)
            {
                if (message == null) message = "Cannot connect to TeamSystem server!";
            }
            else
            {
                message = "TFS connection is valid";
            }

            return message;
        }

        public static void ShowMessage(Page page, string text)
        {
            // build up javascript to inject at the tail end of the page 
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("<script type=\"text/javascript\">");
            stringBuilder.AppendLine(string.Format("alert(\"{0}\");", text));
            stringBuilder.AppendLine("</script>");

            // add to the page 
            page.Controls.Add(new LiteralControl(stringBuilder.ToString()));

            //page.ClientScript.RegisterClientScriptBlock(page.GetType(), "MesageBoxScript", stringBuilder.ToString(), false);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var spPropBag = SPControl.GetContextSite(Context).RootWeb.Properties;

            spPropBag["LobSystem_TFSCredentials"] = this.rdbSPU2.Checked ? "SPU" : "SSS";
            spPropBag["LobSystem_AppID"] = this.sssUserSelector2.Value;

            spPropBag["Attachment_EntityName"] = this.txtAttachment_EntityName.Text;
            spPropBag["Attachment_ShowInItemView"] = this.txtAttachment_ShowInItemView.Text;
            spPropBag["Attachment_ShowInListView"] = this.txtAttachment_ShowInListView.Text;

            spPropBag["LobSystem_Name"] = this.txtLobSystem_Name.Text;
            spPropBag["LobSystem_TFSProjectName"] = this.txtLobSystem_TFSProjectName.Text;
            spPropBag["LobSystem_TFSServerURL"] = this.txtLobSystem_TFSServerURL.Text;

            spPropBag["WorkItem_ReadOnlyFields"] = this.txtWorkItem_ReadOnlyFields.Text;
            spPropBag["WorkItem_RequiredInForms"] = this.txtWorkItem_RequiredInForms.Text;
            spPropBag["WorkItem_ShowInItemView"] = this.txtWorkItem_ShowInItemView.Text;
            spPropBag["WorkItem_ShowInListView"] = this.txtWorkItem_ShowInListView.Text;

            spPropBag.Update();

            //SPUtility.Redirect("../Settings.aspx", SPRedirectFlags.Static, HttpContext.Current);
            Response.Redirect("../Settings.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Settings.aspx");
        }
    }
}
